package com.wn.service;

import com.github.pagehelper.PageHelper;
import com.github.pagehelper.PageInfo;
import com.wn.common.pojo.PageParam;
import com.wn.common.pojo.Role;
import com.wn.common.pojo.Rsp;
import com.wn.common.pojo.User;
import com.wn.common.util.Const;
import com.wn.common.util.JWTUtil;
import com.wn.common.util.MailUtil;
import com.wn.mapper.RoleMapper;
import com.wn.mapper.UserMapper;
import com.wn.web.UserController;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;
import org.springframework.transaction.annotation.Isolation;
import org.springframework.transaction.annotation.Propagation;
import org.springframework.transaction.annotation.Transactional;

import java.util.HashMap;
import java.util.List;
import java.util.Map;
import java.util.regex.Pattern;

/**
 * @BelongsProject: hurricane_travel
 * @BelongsPackage: com.wn.service
 * @Author: lhq
 * @Description:
 */
@Service
@Transactional(propagation = Propagation.REQUIRED,isolation = Isolation.DEFAULT)
public class UserService {

    private static Logger log = LoggerFactory.getLogger(UserController.class);
       @Autowired
       private UserMapper userMapper;

       @Autowired
       private RoleMapper roleMapper;

    /**
     * 登录方法
     * @param
     * @param
     * @return
     */
    public Rsp login(User user) throws Exception {
        //进入登录方法 查询用户是否存在
        log.info("进入登录的user{}",user);
        User userResult = userMapper.selectByAccount(user.getUserAccount());
        if(userResult != null){
            //用户存在
            if(userResult.getUserPassword().equals(user.getUserPassword())){
                //登录成功存token
                String token = JWTUtil.generateToken(userResult, Const.PRIVATE_KEY, 30000 );
                Map<String,Object> map = new HashMap<>();
                map.put("token",token);
                return new Rsp().success(token);
            }else {
                return new Rsp().fail().msg("密码错误！");
            }
        }
        //用户不存在
        return new Rsp().fail().msg("该用户不存在！");

    }

    /**
     * 查询所有的用户
     * @return
     */
    public PageInfo<User> getAllUsers(PageParam<User> pageParam){


        if(!org.apache.commons.lang.StringUtils.isEmpty(pageParam.getSuperSearchKeyWord())){
            //执行高级检索
            //分页
            PageHelper.startPage(pageParam.getPageNum(), pageParam.getPageSize());

            List<Role> roleList = roleMapper.selectAll();

            List<User> userEntityList=userMapper.superSearch(pageParam.getSuperSearchKeyWord());

            PageInfo<User> userEntityPageInfo = new PageInfo<User>(userEntityList);

            return userEntityPageInfo;

        }else{
            //分页
            PageHelper.startPage(pageParam.getPageNum(), pageParam.getPageSize());




            List<User> userEntityList=userMapper.searchSomeByPage((User) pageParam.getModel());

            PageInfo<User> userEntityPageInfo = new PageInfo<User>(userEntityList);

            return userEntityPageInfo;

        }
    }


    /**
     * 逻辑删除指定用户
     * @Param User
     * @return
     */
    public Rsp deleteUser(User user){

            return userMapper.deleteByPrimaryKey(user.getUserId(),user.getUpdateUserId(),user.getUpdateTime()) == 1? new Rsp().success(1) : new Rsp().fail();

    }

    /**
     * 修改指定用户信息
     * @param record
     * @return
     */
    public Rsp updateUser(User record){

        return userMapper.updateByPrimaryKeySelective(record) == 1?
                new Rsp().success(1):new Rsp().fail();
    }

    /**
     * 检测用户名与邮箱是否有效
     * @param account
     * @param email
     * @return
     */
    public Rsp checkUser(String account,String email){
        System.out.println(account+"-----------"+email);
        User record1 = new User();
        User record2 = new User();
        record1.setUserAccount(account);
        record2.setUserEmail(email);
        List<User> users1 = userMapper.searchSomeByPage(record1);
        List<User> users2 = userMapper.searchSomeByPage(record2);
        if(account!=null&&users1.size()>0)
            return Rsp.fail().msg("该用户名已被注册！");
        else if(email!=null&&users2.size()>0)
            return Rsp.fail().msg("该邮箱已有绑定账号！");
        else
            return Rsp.success(null);
    }

    /**
     * 注册方法
     * @param record
     * @return
     */
    public Rsp userRegister(User record){
        System.out.println(record+"---------------");
        User user = userMapper.selectByAccount(record.getUserAccount());
        if(user!=null){
            return Rsp.fail().msg("注册失败，账号已存在");
        }
        else {
            int exe =  userMapper.insertSelective(record);
            if(exe>0)
                return Rsp.success(exe).msg("注册成功！");
            else
                return Rsp.fail().msg("注册失败！");
        }
    }

    /**
     * 登录状态下重置密码
     * @param oldPassword
     * @param newPassword
     * @param id
     * @return
     */
    public int resetPassword(String oldPassword,String newPassword,int id){
        User user = userMapper.selectByPrimaryKey(id);
        if(user.getUserPassword().equals(oldPassword)){
            user.setUserPassword(newPassword);
            return userMapper.updateByPrimaryKey(user);
        }
        else
            return 0;

    }

    /**
     * 根据账号查询用户
     * @param account
     * @return
     */
    public User selectUserByAccount(String account){
        return userMapper.selectByAccount(account);
    }

    /**
     * 修改密码
     * @param account
     * @param newPassword
     * @return
     */
    public Rsp updataUserPassword(String account,String newPassword){
        User user = selectUserByAccount(account);
        if(user==null)
            return Rsp.fail().msg("不存在该用户信息！");
        else {
            //执行密码更新操作
            return userMapper.upNewPasswordByUserAccount(account,newPassword) == 1?
                        new Rsp().success(1): new Rsp().fail().msg("修改密码失败！");
        }
    }


    public Rsp updateStatus(User user){
        if(user.getUserStatus().equals("0"))
           user.setUserStatus("1");
        else
            user.setUserStatus("0");
        int exe = userMapper.updateByPrimaryKeySelective(user);
        if(exe>0)
            return Rsp.success(exe).msg("修改成功！");
        else
            return Rsp.fail().msg("修改失败！");
    }

    /**
     * 根据userid查询出该用户的权限名
     * @param userId
     */
    public User getUserRole(Integer userId) {

        return userMapper.getUserRole(userId);
    }

    public Rsp sendEmail(String email){
        String arr ="ABCDEFGHIJKLMNOPQRSTUVWXYZabcdefghijklmnopqrstuvwxyz0123456789";
        String code = "";
        for(int i=0;i<8;i++)
         code += arr.charAt((int)(Math.random()*(arr.length())));
        System.out.println(email+"-----------------"+code);

        MailUtil.sendEmail(email,code);

        return Rsp.success(code);
    }

    public Rsp unbundling(User user){
        System.out.println(user+"-----------");
        int userId = user.getUserId();
        String userPhone = user.getUserPhone();
        String userEmail = user.getUserEmail();
        String userIdcard = user.getUserIdcard();

        String mobileReg = "1[345678][0-9]{9}";
        Pattern mobilePattern= Pattern.compile(mobileReg);
        if(userPhone!=null&&(!mobilePattern.matcher(userPhone).matches())){
            return Rsp.fail().msg("手机号格式错误！");
        }
        String emailReg = "\\w{1,}@\\w{1,}\\.\\w{2,4}";
        Pattern emailPattern = Pattern.compile(emailReg);
        if (userEmail!=null&&(!emailPattern.matcher(userEmail).matches()) ) {
            return Rsp.fail().msg("邮箱格式错误！");
        }
        String idCardReg = "[1-9]\\d{5}(18|19|([23]\\d))\\d{2}((0[1-9])|(10|11|12))(([0-2][1-9])|10|20|30|31)\\d{3}[0-9Xx]";
        Pattern idCardPattern = Pattern.compile(idCardReg);
        if(userIdcard!=null&&(!idCardPattern.matcher(userIdcard).matches())){
            return Rsp.fail().msg("身份证号格式错误！");
        }
        List<User> userList= userMapper.searchSomeByPage(null);
        for(User u:userList){
            if(u.getUserId()!=userId) {
                if (userEmail != null && userEmail.equals(u.getUserEmail()))
                    return Rsp.fail().msg("对不起，该邮箱已绑定其他账号！");
                if (userPhone != null && userPhone.equals(u.getUserPhone()))
                    return Rsp.fail().msg("对不起，该手机已绑定其他账号！");
                if (userIdcard != null && userIdcard.equals(u.getUserIdcard()))
                    return Rsp.fail().msg("对不起,该身份证号已绑定其他账号！");
            }
        }
        int exe =userMapper.unbunding(userEmail,userPhone,userIdcard,userId);
        if(exe>0)
            return Rsp.success(null).msg("修改成功！");
        else
            return Rsp.fail().msg("网络出错!");

    }

}
